<template>
<div class="groupComWrapper ui form">
  <p>
    <button class="ui icon button tiny" @click.prevent="addGroup()">{{btnTitle}}<i class="icon plus"></i>
      </button>
    <button v-if="is_auth" class="ui icon button tiny" @click.prevent.stop="syncGroup()">同步分组<i class="icon icon-iconfonttongbu"></i>
      </button>
  </p>


    <div class="ui segment">
        <div class="ui top attached label">分组排序</div>
        <draggable element="div" v-model="group" :options="dragOptions" :move="onMove" @start="isDragging=true" @end="isDragging=false" @change="hlChange_group">
            <transition-group type="transition" :name="'flip-list'" tag="div">

                <div v-for="(val,index) in group" class="ui compact message" :key="index">
                    <div class="">{{val}}</div>
                </div>
            </transition-group>
        </draggable>
    </div>

    <draggable element="div" v-model="attr" :options="dragOptions" :move="onMove" @start="isDragging=true" @end="isDragging=false" @change="hlChange">
        <transition-group type="transition" :name="'flip-list'" tag="div">

            <div v-for="(val,index) in attr" class="ui compact message" :key="index">
                <div class="">{{val.title}}</div>
            </div>
        </transition-group>
    </draggable>

  <div v-for="(g,gind) in group" class="ui vertical stackable menu" @dblclick.stop.prevent='toRemove(gind)'>
    <div class="header item"><i class="icon remove circle" @click="toRemove(gind)"></i><input type="text" placeholder='请输入组名' v-model="group[gind]">
    </div>
    <draggable element="div" v-model="attr_group[gind]" :options="dragOptions" :move="onMove" @start="isDragging=true" @end="isDragging=false" @change="hlChange">
      <transition-group type="transition" :name="'flip-list'" tag="div">
        <div v-for="(val,index) in attr_group[gind]" class="item" :key="index">
          {{val.title}}
          <i class="icon remove" @click="removeItem(gind,index)"></i>
        </div>
      </transition-group>
    </draggable>
  </div>
</div>
</template>

<script type="text/ecmascript-6">
import tool from 'src/util/tool';
import util from '_util/index';
import RP from 'src/util/common/attr_sort';
import draggable from 'vuedraggable'

const IMGPRE = tool.IMGPRE

export default {
  data() {
    return {
      // vals: []
      plist: [],
      attr: [],
      // attr2: [],
      attr_group: [],
      group: [],
        mgroup_all: {},
        grouped_all: {},
      group_str: '',
      attr_group_str: '',
        _attr_group_str: '',
        _group_str: '',
      editable: true,
      isDragging: false,
      show: true,
      delayedDragging: false
    }
  },
  components: {
    draggable,
  },
  methods: {
    removeItem(gind, index) {
      let removed = this.attr_group[gind].splice(index, 1)[0]
      if (removed.id != -1)
        this.attr.push(removed)
      if (this.attr_group[gind].length == 0) {
        this.group.splice(gind, 1)
        this.attr_group.splice(gind, 1)
      }
    },
    toRemove(index) {
      this.group.splice(index, 1);
      let removed = this.attr_group.splice(index, 1)
      if (removed[0].length > 0) {
        removed[0].forEach(item => {
          if (item.id != -1)
            this.attr.push(item)
        });
      }

    },
    filter_attr(attr,f=0) {
      attr = attr || this.attr_group_str
      let has = attr?JSON.parse(attr):[]
      let tmp = [];
      tmp = has.reduce((coll, item) => {
        let rs = coll.concat(item)
        return rs;
      }, tmp);
      // tool.cl(has)
      // tool.cl(tmp)
        let myattr = f ? this.attr_all : this.attr;
      this.attr = myattr.filter(item => {
        return !tmp.contains(item.id)
      });
    },
    toAddMenuGroup() {
      RP.yes_event(this)

      let eventVue = util.store.get(this,'eventVue');
      setTimeout(() => {
        eventVue.$emit('showSearch', 'menu_group')
      }, 100)
    },
    showPop() {
        let info = {
            mid: 9,
            yes_event: 'toAddMenuGroup_' + this.top_id
        };
        util.showEditPop(this, info);
    },
    pro_attr_group_str() {
      let hled = this.attr_group.map(group => {
        return group.map(field => {
          return field.id
        })
      })
      this.attr_group_str = JSON.stringify(hled)
      this.setEditvo('attr_group_str')
    },
    pro_group_str() {
      this.group_str = JSON.stringify(this.group)
      this.setEditvo('group_str')
    },
      get_mgroup_all(clb) {
          let info = util.store.get(this, 'mgroup', 'edit');
          if(info) {
              let {mgroup:mgroup_all,grouped:grouped_all} = info;
              if(mgroup_all&&grouped_all) {
                  this.mgroup_all = mgroup_all;
                  this.grouped_all = grouped_all;
                  clb();
                  return;
              }
          }


          let url = tool.getApi(this, 'Editget', 'getMenuFields');
          let param = {
              is_auth: false,
              menu_group:null
          };
          util.getDataCom(this, url, param, (data) => {
              this.mgroup_all = data.mgroup;
              this.grouped_all = data.grouped
              util.store.commit(this,'set_mgroup',{mgroup:this.mgroup_all,grouped:this.grouped_all},'edit');
              clb();
          });
      },
      syncGroup() {
          this.get_mgroup_all(()=> {
              if(!this.mgroup_all||!this.grouped_all||!this.mgroup_all[this.top_id]) {
                  util.showMsg(this, 'error', '同步失败');
                  return;
              }
              let {attr_group_str,group_str} = this.mgroup_all[this.top_id];
//          tool.cl('attr_group_str,group_str', attr_group_str, group_str);
              this._group_str = group_str;
              this._attr_group_str = attr_group_str;
              this.init(1);
              this.filter_attr(null,1);
          });


    },
    addGroup() {
      this.showPop()
    },
    setEditvo(key) {
      let vo = this.$store.state.global.menuGroup
      vo[this.top_id] = vo[this.top_id] || {}
      vo[this.top_id][key] = this[key];
      util.store.commit(this,'setMenuGroup', vo)
    },
      hlChange_group({moved}) {
          let {newIndex, oldIndex} = moved;

          let new_data = this.attr_group[newIndex];
          util.set(this, 'attr_group', newIndex, this.attr_group[oldIndex]);
          util.set(this, 'attr_group', oldIndex, new_data);
//          this.attr_group[newIndex]=this.attr_group[oldIndex];
//          this.attr_group[oldIndex]=new_data;
    },
    hlChange() {
    },
    onMove({
      relatedContext,
      draggedContext
    }) {
      const relatedElement = relatedContext.element;
      const draggedElement = draggedContext.element;
      let rl = relatedContext.list.length
      let reTitle = relatedElement ? relatedElement.title : ''
      if (rl == 1 && reTitle == '占位（请忽略）') {
        // tool.cl('fff')
        relatedContext.list.splice(0, 1)
      }
      // tool.cl(relatedContext, draggedContext)
      return true
    },
    init2() {
      let l = this.attr_group.length

      let copyTarget = this.attr_group[0] ? this.attr_group[0][0] : this.attr[0]

      let first = util.deepCopy(copyTarget)

      this.attr_group[0] = []

      this.attr_group[0] = [first]
      this.attr_group[0][0].id = -1;
      this.attr_group[0][0].title = '占位（请忽略）';

      this.pro_attr_group_str()
    },
    init(f=0) {
      if (this.attr) {
        if (this._group_str) {

            let fields = f ? this.grouped_all : this.grouped;

            let group = this._group_str ? JSON.parse(this._group_str) : [];
          // tool.cl(group)
          // tool.cl(group[0])
          // tool.cl(Boolean(group[0]))
          if (group.length > 0 && group[0]) {
            // tool.cl('in', group)
            this.group = group
            this.pro_group_str()

            let attr_group = this._attr_group_str?JSON.parse(this._attr_group_str):[]
//             tool.cl('attr_group:',attr_group)
            if (attr_group[0]&&attr_group[0][0] && attr_group[0][0] != -1) {
              let tmp = {}
              fields.forEach(field => {

                tmp[field.id] = {
                  id: field.id,
                  title: field.title
                }

              })
//                tool.cl('tmp:', tmp);


              this.attr_group = attr_group.map(group => {
                group = group.filter((id) => {
                  return tmp[id]
                })
                return group.map(id => {
                  return {
                    id: id,
                    title: tmp[id].title
                  }
                })
              })

              this.pro_attr_group_str()


            } else {
              // this.group_init(fields, 1)
            }
          } else {
            // this.group_init(fields)
          }

        } else {
          // this.group_init(this.attr)
        }

        // if (this.attr_group.length == 0)
        //   this.init2()
        // else {
        //   // this.filter_attr()
        // }

        this.show = true
      }
    },
    group_init(fields, f) {
      let maped = fields.map(field => {
        return {
          id: field.id,
          title: field.title
        }
      })
      this.attr_group[0] = maped

      if (f) {
        this.pro_attr_group_str()
      } else {
        this.pro_attr_group_str()
        this.pro_group_str()
      }

    }
  },
  watch: {
    group: function(val, old) {
      if (val) {
        this.pro_group_str()
      }
    },
    attr_group: function(val, old) {
      if (val) {

        this.pro_attr_group_str()

      }
    },
    isDragging(newValue) {
      if (newValue) {
        this.delayedDragging = true
        return
      }
      this.$nextTick(() => {
        this.delayedDragging = false
      })
    }
  },
  computed: {
    dragOptions() {
      return {
        animation: 0,
        group: 'description',
        disabled: !this.editable,
        ghostClass: 'ghost'
      };
    },
  },
  props: ['btnTitle', 'top_id','attr_all','is_auth', '_attr', 'grouped', '_group_str2', '_attr_group_str2'],
  created() {
      this.attr = this._attr;
      this._group_str = this._group_str2;
      this._attr_group_str = this._attr_group_str2;
    this.init()

    // this.attr = this.attr2 = this.attr_group[0] = util.getBindField(this.mid)

    let eventVue = util.store.get(this,'eventVue');
    eventVue.$on('toAddMenuGroup_' + this.top_id, this.toAddMenuGroup)
  },
  destroyed() {
    let eventVue = util.store.get(this,'eventVue');
    eventVue.$off('toAddMenuGroup_' + this.top_id, this.toAddMenuGroup)
  },
  mounted() {}
};
</script>

<style rel="stylesheet/less" lang="less" scoped>@import "../../common/style/mixin";
@dir: "edit/";

.flip-list-move {
    transition: transform 0.5s;
}

.ui.vertical.menu {
    display: inline-block;
    vertical-align: top;
    margin-left: 10px;

}

.groupComWrapper {
    .sortMenu();
}
</style>
